package com.ra.coupon;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.jdbc.ReturningWork;
import org.springframework.stereotype.Service;

import com.espirit.eap.manager.DictionaryService;
import com.espirit.eap.manager.TaskSchedulerService;
import com.espirit.eap.sa.LoginUser;
import com.espirit.eap.sa.LoginUserService;
import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.oosearch.Condition;
import com.googlecode.cswish.struts.spring.GenericService;
import com.ra.pay.alipay.AlipayUtil;
import com.ra.util.DateTimeUtil;
import com.ra.util.SmsLog;
import com.ra.util.SmsService;

@Service
public class UserCouponService {
	
	private static final Log logger = LogFactory.getLog(AlipayUtil.class);

	@Resource
	private GenericService genericService;
	
	@Resource
	private LoginUserService loginUserService;
	
	@Resource
	private DictionaryService dictionaryService;
	
	@Resource
	private TaskSchedulerService taskSchedulerService;
	
	@Resource
	private SmsService smsService;
	
	/**每个手机号领取的金额为50元,对应id为1**/
	public static Integer COUPONID = 1;
	
	/**裂变券的id**/
	private static int[] arrFission = new int[] { 2, 3, 4 };
	
	/**
	 * 给分享人增加优惠券裂变记录，金额为10,15,20元其中一种
	 * @param model
	 * @return
	 */
	public void addFissionCoupon(UserCoupon model) {
		UserCoupon shareModel = new UserCoupon();
		shareModel.setFissioned(true);
		shareModel.setPhone(model.getSharePhone());
		// 查询model.getSharePhone()是否有裂变券
		int size = genericService.searchByModel(shareModel, Condition.DEFAULT)
				.getData().size();
		if (size == 0) {
			// 新增裂变代金券
			shareModel.setCouponCode(createCouponCode());
			shareModel.setStatus(UserCoupon.STATUS_AVAILABLE);
			shareModel.setBeginTime(Calendar.getInstance().getTime());
			shareModel.setEndTime(getEndTime());
			shareModel.setNewCoupon(true);
			shareModel.setUser(loginUserService.getLoginUser());
			shareModel.setCreateTime(Calendar.getInstance().getTime());
			// 随机取所属券的id
			int num = (int) (arrFission.length * Math.random());
			Coupon coupon = new Coupon();
			coupon.setId(arrFission[num]);
			shareModel.setCoupon(coupon);
			this.genericService.add(shareModel);
			// 新增裂变券后发送一条短信提示
			sendMsg(shareModel);
		}
	}
	
	/**
	 *  新增裂变券后发送一条短信提示
	 * @param shareModel
	 */
	public void sendMsg(UserCoupon shareModel) {
		String smsContent = "尊敬的好好租用户，您分享出去的租房券已被好友领取，恭喜您再获得一张租房券，请到“好好租APP-我的-我的租房券”查看！";
		SmsLog smsLog = smsService
				.sendMessage(shareModel.getPhone(),
						SmsLog.TYPE_REMINDER_LETTER, smsContent, true,
						loginUserService.getLoginUser(),
						SmsService.CHANEL_NORMAL, null);
		if (smsLog == null) {
			logger.error("给分享人增加优惠券裂变记录后，提示短信发送出错！");
		}
	}
	
	/**
	 * 获取当前登录用户
	 * 这里要实现单点登录
	 * @return
	 */
	public LoginUser goInvitePage(){
		return loginUserService.getLoginUser();
	}
	
	/**
	 * 增加用户领取优惠券记录
	 * @param model
	 * @return
	 */
	@Rest(type = "add")
	public UserCoupon addUserCoupon(UserCoupon model) {
		// 查询model.getPhone()是否有领取过券
		UserCoupon tempModel = new UserCoupon();
		tempModel.setPhone(model.getPhone());
		int size = genericService.searchByModel(tempModel, Condition.DEFAULT).getData().size();
		// 如果有，则返回已领取的券,如果没有，则新增加一个券
		if (size == 0) {
			// 新增一个券的同时，判断是否是分享券，如果是，给分享给自己的人产生一个裂变券
			if (model.getSharePhone() != null && !"".equals(model.getSharePhone())) {
				addFissionCoupon(model);
			}
			model.setCouponCode(createCouponCode());// 设置编号
			model.setStatus(UserCoupon.STATUS_AVAILABLE);// 设置优惠券的状态为可用
			model.setBeginTime(Calendar.getInstance().getTime());// 设置开始时间
			model.setEndTime(getEndTime());// 设置结束时间
			model.setUser(loginUserService.getLoginUser());// 设置所属人
			model.setCreateTime(Calendar.getInstance().getTime());// 设置领券时间
			Coupon coupon = new Coupon();
			coupon.setId(COUPONID);
			model.setCoupon(coupon);
			model.setFissioned(false);
			model.setNewCoupon(true);
			// 设置所属券
			model = this.genericService.add(model);
			model.setFetched(true);// 设置领取成功标志
		} else {
			model.setFetched(false);
		}
		return model;
	}
	
	/**
	 * 获得结束时间
	 * @return
	 */
	private Date getEndTime(){
		Calendar calCurrent = Calendar.getInstance();    
        calCurrent.add(Calendar.MONTH, 2);
        return calCurrent.getTime();
	}

	/**
	 * 随机生成优惠券的编号()
	 * 
	 * @return
	 */
	private String createCouponCode() {
		Calendar calCurrent = Calendar.getInstance();
		String code = DateTimeUtil.formatDateTime(calCurrent.getTime(), "yyyyMMddHHmmss");
		String random = String.format("%03d", (int) (1 + Math.random() * 1000));
		return code + random;
	}
	
	/**
	 * 按状态返回优惠券个数
	 * @param status
	 * @return
	 */
	public int getUserCouponByState(Integer status){
		int result = 0;
		List<UserCoupon> userCoupons = searchUserCoupon(status);
		if (CollectionUtils.isNotEmpty(userCoupons)) {
			result = userCoupons.size();
		}
		return result;
	}
	
	/**
	 * 根据用户的电话查询用户领取的优惠券
	 * @return
	 */
	@Rest(type = "search")
	public List<UserCoupon> searchUserCoupon(Integer status) {
		UserCoupon model = new UserCoupon();
		model.setPhone(loginUserService.getLoginUser().getName());
		if (status != null) {
			model.setStatus(status);
		}
		
		List<UserCoupon> userCoupons = genericService.searchAll(model).getData();
		
		if (userCoupons != null && userCoupons.size() > 0) {
			for (UserCoupon userCoupon : userCoupons) {
				if (userCoupon.getNewCoupon()) {
					userCoupon.setNewCoupon(false);
					genericService.merge(userCoupon);
				}
			}
		}
		return userCoupons;
	}
	
	/**
	 * 查询当前登录用户未查看过的优惠券的数目
	 * @return
	 */
	public int getCouponCount(){   
		UserCoupon model = new UserCoupon();
		model.setPhone(loginUserService.getLoginUser().getName());
		model.setNewCoupon(true);
		return genericService.searchByModel(model, Condition.DEFAULT).getData().size();
	} 
	
	/**
	 * 根据优惠券的使用情况返回用户优惠券
	 * @return
	 */
	public Map<String, List<UserCoupon>> searchUserCouponByProperties() {
		List<UserCoupon> listUserCoupon = new ArrayList<UserCoupon>();
		listUserCoupon = searchUserCoupon(null);
		List<UserCoupon> listUnUsedUserCoupon = new ArrayList<UserCoupon>();
		List<UserCoupon> listUsedUserCoupon = new ArrayList<UserCoupon>();
		List<UserCoupon> listExpiredUserCoupon = new ArrayList<UserCoupon>();
		Map<String, List<UserCoupon>> map = new HashMap<String, List<UserCoupon>>();
		Iterator<UserCoupon> it = listUserCoupon.iterator();
		while (it.hasNext()) {
			UserCoupon userCoupon = (UserCoupon) it.next();
			
			if (userCoupon.getStatus() == 0) {
				listExpiredUserCoupon.add(userCoupon);
			}
			
			if (userCoupon.getStatus() == 1) {
				listUnUsedUserCoupon.add(userCoupon);
			}

			if (userCoupon.getStatus() == 2) {
				listUsedUserCoupon.add(userCoupon);
			}

		}
		map.put("unUsed", listUnUsedUserCoupon);
		map.put("used", listUsedUserCoupon);
		map.put("expired", listExpiredUserCoupon);
		return map;
	}
	
	/**
	 * 获取活动的截止时间
	 * @param name
	 * @return
	 */
	@Rest(simpleServiceName = "anonymity", type = "free")
	public String getActivityEndTime(String name){
		return dictionaryService.getValueByTypeName("time", name);
	}
	
	/**
	 * 根据登录用户以及查询条件查询优惠券
	 * @param model
	 * @return 优惠券集合
	 */
	public List<UserCoupon> searchCouponsByLoginUser(UserCoupon model) {
		if(model == null) {
			model = new UserCoupon();
		}
		model.setPhone(loginUserService.getLoginUser().getName());
		if(model.getStatus() != null) {
			model.setStatus(model.getStatus());
		} 
		List<UserCoupon> userCoupons = genericService.searchAll(model).getData();
		
		if (userCoupons != null && userCoupons.size() > 0) {
			for (UserCoupon userCoupon : userCoupons) {
				if (userCoupon.getNewCoupon()) {
					userCoupon.setNewCoupon(false);
					genericService.merge(userCoupon);
				}
			}
		}
		return userCoupons;
	}
	
	/**
	 * 根据登录用户查询可用优惠券
	 * @param model
	 * @return 可用优惠券集合
	 */
	public List<UserCoupon> searchAvailableCouponsByLoginUser() {
		UserCoupon model = new UserCoupon();
		model.setPhone(loginUserService.getLoginUser().getName());
		model.setStatus(UserCoupon.STATUS_AVAILABLE);
		List<UserCoupon> userCoupons = genericService.searchAll(model).getData();
		
		if (userCoupons != null && userCoupons.size() > 0) {
			for (UserCoupon userCoupon : userCoupons) {
				if (userCoupon.getNewCoupon()) {
					userCoupon.setNewCoupon(false);
					genericService.merge(userCoupon);
				}
			}
		}
		return userCoupons;
	}
	
	/**
	 * 修改优惠券的状态（ 定时器）
	 * 
	 */
	public void updateUserCouponState(){
		
		genericService.doReturningWork(new ReturningWork<String>() {
			@Override
			public String execute(Connection connection) throws SQLException {
				boolean ret = connection.getAutoCommit();
				connection.setAutoCommit(false);
				
				String sql = "update ra_usercoupon r set r.status = "+UserCoupon.STATUS_OVERDUE+" where r.status = "+UserCoupon.STATUS_AVAILABLE +" and r.endTime<?";
	            PreparedStatement ps = connection.prepareStatement(sql);
	            ps.setDate(1, new java.sql.Date(Calendar.getInstance().getTime().getTime()));
				int[] rets = ps.executeBatch();
				ps.close();
	            connection.commit();
	            connection.setAutoCommit(ret);
				return null;
			}
		});
		taskSchedulerService.updateTaskSchedulerRunTime(this.getClass(), "updateApartmentLowPrice");
	}
	
}
